<?php
namespace app\common\logic;

use think\facade\Db;
class Stock{
    /**
     * 商品库存操作日志
     * @param int $muid 操作 用户ID
     * @param int $stock 更改库存数
     * @param array $goods 库存商品
     * @param string $order_sn 订单编号
     */
    function update_stock_log($muid, $stock = 1, $goods, $order_sn = '')
    {
        $suid = Db::name('goods')->where('goods_id',$goods['goods_id'])->value('sid');
        $data = [];
        $data['supplier_id'] = $suid;
        $data['ctime'] = time();
        $data['stock'] = $stock;
        $data['muid'] = $muid;
        $data['goods_id'] = $goods['goods_id'];
        $data['goods_name'] = $goods['goods_name'];
        $data['goods_spec'] = empty($goods['spec_key_name']) ?'' : $goods['spec_key_name'];
        $data['spec_goods_id'] = $goods['spec_goods_id']?$goods['spec_goods_id']:'';

        //订单号
        $data['order_sn'] = $order_sn;
        $rs = Db::name('stock_log')->insert($data);
        if(!$rs){
            return ['status'=>0,'msg'=>'添加库存日志失败'];
        }

        //减少产品库存
        if($order_sn){
            $data = array('store_count'=>array('exp','`store_count`+'.$stock));
            if($goods['spec_goods_id']>0){
                $rs = Db::name('spec_goods_price')->where('item_id',$goods['spec_goods_id'])->inc('store_count',$stock)->update();
            }
            $rs = Db::name('goods')->where('goods_id',$goods['goods_id'])->inc('store_count',$stock)->update();
        }

        if(!$rs){
            return ['status'=>0,'msg'=>'更新产品库存失败'];
        }

        return ['status'=>1];
    }
}
